package com.sap.sap_mangers.filter;

import com.alibaba.fastjson.JSON;
import com.sap.sap_mangers.domain.LoginUser;
import com.sap.sap_mangers.until.ConstantUntil;
import com.sap.sap_mangers.until.JwtUtil;
import com.sap.sap_mangers.until.RedisCache;
import com.sap.sap_mangers.until.UrlUntil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * @author 阿东
 * @date 2022/7/5 [20:18]
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestUri = request.getRequestURI();
        if (
                Objects.equals(requestUri, UrlUntil.LOGIN_URL) ||
                Objects.equals(requestUri, UrlUntil.REGISTER_URL) ||
                Objects.equals(requestUri, UrlUntil.FORGOT_PASSWORD) ||
                Objects.equals(requestUri, UrlUntil.GENERATE_CODE)||
                Objects.equals(requestUri, UrlUntil.ADDQQ)
        ) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        String userid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            return;
        }
        //从redis中获取用户信息
        Map<String, Object> cacheMap = redisCache.getCacheMap(ConstantUntil.SAP_LOGIN);
        String userJson = (String) cacheMap.get(userid);
        LoginUser loginUser = JSON.parseObject(userJson, LoginUser.class);
        if (Objects.isNull(loginUser)) {
            throw new RuntimeException("用户未登录");
        }
        //存入SecurityContextHolder
        //TODO 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }
}
